package mamikeji.liaowa.ui.fragment.main_todo;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import mamikeji.liaowa.R;
import mamikeji.liaowa.bean.MainBean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.MainActivity;
import mamikeji.liaowa.ui.adapter.TodoChildSelectAdapter;
import mamikeji.liaowa.ui.fragment.BaseFragment;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;

/**
 * Created by 廉冲-android开发 on 2017/8/5.
 */
public class ToDo_RecyclerFragment extends BaseFragment {
    private static final String TAG = "ToDo_RecyclerFragment";
    View mView;
    @BindView(R.id.textView_todo_recyler_title)
    TextView textViewTodoRecylerTitle;
    @BindView(R.id.recycleListView_single)
    RecyclerView recycleListViewSingle;

    MainBean.DynamicEntity.TaskconfigEntity listEntity;
    @BindView(R.id.textView_todo_r_index)
    TextView textViewTodoRIndex;
    @BindView(R.id.textView_todo_r_max)
    TextView textViewTodoRMax;
    private int num, max;

    List<TodoChildSelectAdapter.ViewHolder> viewList = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_todo_recycler, container, false);
        ButterKnife.bind(this, mView);
        getBase();

        listEntity = (MainBean.DynamicEntity.TaskconfigEntity) getArguments().getSerializable("todo");
        num = getArguments().getInt("todo_vp_num");
        max = getArguments().getInt("todo_vp_max");

        init();
        return mView;
    }

    public static final ToDo_RecyclerFragment Instance(Serializable serializable, int num, int max) {
        ToDo_RecyclerFragment toDo_recyclerFragment = new ToDo_RecyclerFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("todo", serializable);
        bundle.putInt("todo_vp_num", num);
        bundle.putInt("todo_vp_max", max);
        toDo_recyclerFragment.setArguments(bundle);
        return toDo_recyclerFragment;
    }

    private void init() {
        textViewTodoRIndex.setText(num+1+"");
        textViewTodoRMax.setText(max+"");
        textViewTodoRecylerTitle.setText(listEntity.getTitle());
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        if (listEntity.getType() == 4) {
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        } else {
            linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        }
        recycleListViewSingle.setLayoutManager(linearLayoutManager);

        final TodoChildSelectAdapter childSelectAdapter = new TodoChildSelectAdapter(getContext(), listEntity.getAnswers());
        recycleListViewSingle.setAdapter(childSelectAdapter);
        childSelectAdapter.setOnItemClickListener(new TodoChildSelectAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, List<TodoChildSelectAdapter.ViewHolder> viewHolderList) {
                viewList.clear();
                viewList.addAll(viewHolderList);
                if (listEntity.getType() == 3) {
                    onMultipleItemClick(position);
                } else {
                    onSingleItemClick(position);
                }
            }
        });
    }

    private void onMultipleItemClick(int position) {
        int selected = listEntity.getAnswers().get(position).getScoresection();
        if (selected == 0) {
            int count = 0;
            for (int i = 0; i < listEntity.getAnswers().size(); i++) {
                if (listEntity.getAnswers().get(i).getScoresection() == 1) {
                    count++;
                }
            }
            if (count >= 5) {
                ForToast.showToast("最多只能选择5个");
                return;
            }
            listEntity.getAnswers().get(position).setIschoice(1);
        } else {
            listEntity.getAnswers().get(position).setIschoice(0);
        }
        updateToDoData(position, listEntity.getType());
    }

    private void onSingleItemClick(int position) {
        int selected = listEntity.getAnswers().get(position).getIschoice();
        if (selected == 0) {
            listEntity.getAnswers().get(position).setIschoice(1);
            for (int i = 0; i < listEntity.getAnswers().size(); i++) {
                if (i != position) {
                    listEntity.getAnswers().get(i).setIschoice(0);
                }
            }
        } else {
            listEntity.getAnswers().get(position).setIschoice(0);
        }
        updateToDoData(position, listEntity.getType());
    }

    public void updateToDoData(final int position, final int ttype) {
        for (int i = 0 ; i<viewList.size() ; i++){
            viewList.get(i).tv.setOnClickListener(null);
        }
        MainBean.DynamicEntity.TaskconfigEntity.AnswersEntity childBean = listEntity.getAnswers().get(position);
        Map<String, String> formMap = new HashMap<>();
        formMap.put("userid", ForPreference.getString(ForContents.USER_CODE));
        formMap.put("tid", listEntity.getTimuid() + "");
        formMap.put("timeid", ForPreference.getString(ForContents.WA_timeCode));
        formMap.put("oid", childBean.getAnswerid() + "");
        formMap.put("scoreLv", childBean.getScoresection() + "");
        formMap.put("score", listEntity.getScore() + "");
        formMap.put("ttype", ttype + "");
        formMap.put("config_id", listEntity.getConfigid());
        formMap.put("category", listEntity.getCategory() + "");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.TODO_ADD, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG + "updateToDoData", "" + e.getMessage());
                ForToast.showToast(R.string.intent_error);
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        ((MainActivity) getActivity()).getToDo_vp(num , false);
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void getStatic(int position , boolean bool){
        ForLog.i("getStaticgetStatic：",""+position+"    "+bool+"    "+listEntity.getType());
        if (bool){
            //成功
            if (listEntity.getType() == 2 || listEntity.getType() == 4){
                for (int i = 0 ; i < viewList.size() ; i++){
                    ForLog.i("getStaticgetStatic：",""+listEntity.getAnswers().get(i).getIschoice());
                    if(listEntity.getAnswers().get(i).getIschoice()!=1){
                        viewList.get(i).tv.setBackgroundResource(R.drawable.shape_todo_btn_bg_sel);
                        viewList.get(i).tv.setTextColor(getContext().getResources().getColor(R.color.color_ffffff));
                    }else{
                        viewList.get(i).tv.setBackgroundResource(R.drawable.shape_todo_btn_bg_null);
                        viewList.get(i).tv.setTextColor(getContext().getResources().getColor(R.color.color_ffffff));
                    }
                }
            }else {
                if(listEntity.getAnswers().get(position).getIschoice()!=1){
                    viewList.get(position).tv.setBackgroundResource(R.drawable.shape_todo_btn_bg_sel);
                    viewList.get(position).tv.setTextColor(getContext().getResources().getColor(R.color.color_ffffff));
                }else{
                    viewList.get(position).tv.setBackgroundResource(R.drawable.shape_todo_btn_bg_null);
                    viewList.get(position).tv.setTextColor(getContext().getResources().getColor(R.color.color_ffffff));
                }
            }
        }else {
            //失败
            for (int i = 0 ; i < viewList.size() ; i++){
                if(listEntity.getAnswers().get(i).getIschoice()==1){
                    viewList.get(i).tv.setBackgroundResource(R.drawable.shape_todo_btn_bg_sel);
                    viewList.get(i).tv.setTextColor(getContext().getResources().getColor(R.color.color_ffffff));
                }else{
                    viewList.get(i).tv.setBackgroundResource(R.drawable.shape_todo_btn_bg_null);
                    viewList.get(i).tv.setTextColor(getContext().getResources().getColor(R.color.color_ffffff));
                }
            }
        }
    }
}
